package com.yuyou.hxyy.service.api.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.yuyou.hxyy.service.api.bean.LoginRedisObj;
import com.yuyou.hxyy.service.api.bean.ResBoolSimpleInfo;
import com.yuyou.hxyy.service.api.cons.CommCons;
import com.yuyou.hxyy.service.api.entity.AuthUser;
import com.yuyou.hxyy.service.api.enums.UserEnums;
import com.yuyou.hxyy.service.api.mess.LoginMess;
import com.yuyou.hxyy.service.api.service.IAuthUserService;
import com.yuyou.hxyy.service.api.service.ICaptchaService;
import com.yuyou.hxyy.service.api.service.ILoginService;
import com.yuyou.hxyy.service.api.service.IUserWordRepoService;
import com.yuyou.hxyy.service.api.util.DateUtil;
import com.yuyou.hxyy.service.api.util.DefindBeanUtils;
import com.yuyou.hxyy.service.api.util.MD5Util;
import com.yuyou.hxyy.service.api.util.TokenUtil;
import com.yuyou.hxyy.service.api.vo.req.ReqLogin;
import com.yuyou.hxyy.service.api.vo.req.ReqPassWordReset;
import com.yuyou.hxyy.service.api.vo.req.ReqPassWordUpdate;
import com.yuyou.hxyy.service.api.vo.resp.RespLogin;
import com.yuyou.hxyy.service.api.vo.resp.UserWordRepoVo;

@Service
public class LoginServiceImpl implements ILoginService{

	
	@Autowired
	private ICaptchaService captchaService;
	
	@Autowired
	private IAuthUserService authUserService;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private IUserWordRepoService userWordRepoService;
	
	@Override
	public ResBoolSimpleInfo<RespLogin> login(ReqLogin reqLogin) {
		ResBoolSimpleInfo<RespLogin> res=new ResBoolSimpleInfo<RespLogin>();
		RespLogin respLogin=new RespLogin();
		
		AuthUser authUser=authUserService.seleteByAccount7Type(reqLogin.getPhone(),reqLogin.getUserType());
		if(authUser==null){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
			return res;
		}
					
		if(authUser.getStatus().equals(UserEnums.status.freeze.getValue())){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_STATUS_FREEZE);
			return res;
		}
		
		//学生登录不需要验证码
		if(authUser.getUserType()==UserEnums.userType.manager.getValue()){
			ResBoolSimpleInfo<String> ver=verifyCode(reqLogin);
			if(!ver.isSuccess()){
				res.setSuccess(false);
				res.setMessage(ver.getMessage());
				return res;
			}
		}
	
		AuthUser authUserUpdate = new AuthUser();
		authUserUpdate.setAuthUserId(authUser.getAuthUserId());
		
		//密码		
		if(MD5Util.md5Hex(reqLogin.getPassword(),CommCons.INIT_PASSWORD_ADMIN_SALT).equalsIgnoreCase(authUser.getPassword())){
			//生成token
	        String token = TokenUtil.GenerateToken();  
	        
	        LoginRedisObj obj=new LoginRedisObj(token, authUser.getAuthUserId(), authUser.getUsername(),
	        		authUser.getUserType(),authUser.getUserType()==0?"":"",authUser.getHeadImg());
	        
	        String userIdKey=stringRedisTemplate.opsForValue().get(String.valueOf(authUser.getAuthUserId()));
	        if(!StringUtils.isEmpty(userIdKey)){
		        stringRedisTemplate.delete(userIdKey);	
	        }
	        stringRedisTemplate.opsForValue().set(token, obj.toJson(), CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);	
	        stringRedisTemplate.opsForValue().set(authUser.getAuthUserId().toString(), token, CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);		        
	        
	        DefindBeanUtils.copyProperties(obj, respLogin);
	        respLogin.setUserId(authUser.getAuthUserId());
	        respLogin.setAccessToken(token);
	        			
	     // 成功登录更新最后登录时间，重置失败次数
			authUserUpdate.setLoginTime(DateUtil.now());
			authUserUpdate.setLoginErr(0);
			
			//学生登录不需要验证码
			if(authUser.getUserType()==UserEnums.userType.manager.getValue()){
		        captchaService.cleanOptStat(reqLogin.getPhone());
			}else if(authUser.getUserType()==UserEnums.userType.student.getValue()){
				List<UserWordRepoVo> repoList=userWordRepoService.findLearningList(authUser.getAuthUserId(), 1);
				respLogin.setLearn(repoList.size()>0?1:0);
			}
			
			res.setData(respLogin);
			res.setSuccess(true);
		}else{				
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
			if(authUser.getUserType()==UserEnums.userType.manager.getValue()){
				captchaService.opsStat(reqLogin.getPhone());
			}else if(authUser.getUserType()==UserEnums.userType.student.getValue() && authUser.getLoginErr()>=10){
				authUserUpdate.setStatus(UserEnums.status.freeze.getValue());
			}
			authUserUpdate.setLoginErr(authUser.getLoginErr()+1);
		}
	
		authUserService.updateByPrimaryKeySelective(authUserUpdate);
		
		
		
	return res;
		
		
		
		
		
	}

	

	public ResBoolSimpleInfo<String> verifyCode(ReqLogin reqLogin) {
		ResBoolSimpleInfo<String> res =new ResBoolSimpleInfo<String>();
		boolean need=captchaService.needVerifyCode(reqLogin.getPhone());
		if(need){
			res=captchaService.verifyCode(reqLogin.getToken(), reqLogin.getCaptcha());				
			if(!res.isSuccess()){
				res.setSuccess(false);
				res.setMessage(res.getMessage());
				return res;
			}			
		}
		res.setSuccess(true);
		return res;
	}
	
	@Override
	public ResBoolSimpleInfo<String> updatePass(Long userId,ReqPassWordUpdate reqPassWordUpdate) {	
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();		
		if(!reqPassWordUpdate.getPassword().equals(reqPassWordUpdate.getcPassword())){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_2_PASS_NOT_EQUAL);
			return res;
		}	
		AuthUser authUser=authUserService.selectByPrimaryKey(userId);
		if(authUser==null){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
			return res;
		}		
		if(MD5Util.md5Hex(reqPassWordUpdate.getoPassword(),CommCons.INIT_PASSWORD_ADMIN_SALT).equalsIgnoreCase(authUser.getPassword())){		
			authUser.setPassword(MD5Util.md5Hex(reqPassWordUpdate.getcPassword(),CommCons.INIT_PASSWORD_ADMIN_SALT));
			authUserService.updateByPrimaryKeySelective(authUser);
			res.setSuccess(true);
		}else{
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_OPASS_NOT_EQUAL);
			return res;
		}
		res.setSuccess(true);
		res.setData("操作成功");
		return res;
	}



	@Override
	public ResBoolSimpleInfo<String> resetPass(Long userId,ReqPassWordReset reqPassWordReset) {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();			
		AuthUser authUser=authUserService.selectByPrimaryKey(reqPassWordReset.getUserId());
		if(authUser==null){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
			return res;
		}		
		authUser.setPassword(MD5Util.md5Hex(MD5Util.md5Hex(CommCons.INIT_PASSWORD,CommCons.INIT_PASSWORD_FRONT_SALT),CommCons.INIT_PASSWORD_ADMIN_SALT));
		authUserService.updateByPrimaryKeySelective(authUser);
		res.setData("操作成功");
		res.setSuccess(true);
		return res;
	}
	
	



	

}